//
//  CKCollectionView.swift
//  onemeetingmac
//
//  Created by 张衡 on 2020/3/4.
//  Copyright © 2020 onemeeting. All rights reserved.
//

import Foundation
import TXLiteAVSDK_TRTC_Mac

@objc protocol CKCollectionDelegate {
    @objc func ck_collectionView(_ collectionView: NSCollectionView, didSelectItemsAt indexPaths: Set<IndexPath> ,info: TRTCScreenCaptureSourceInfo)
}

class CKCollectionView: NSView {
    
    var sections:[[TRTCScreenCaptureSourceInfo]] = []
    weak var delegate:CKCollectionDelegate?
    
    lazy var collectionView: NSCollectionView = {
        let flowLayout = NSCollectionViewFlowLayout.init()
        flowLayout.scrollDirection = .vertical  // 设置排列方式
        flowLayout.minimumLineSpacing = 10
        flowLayout.minimumInteritemSpacing = 0
        flowLayout.itemSize = NSSize.init(width: 150, height: 160)
        let collection = NSCollectionView.init()
        collection.collectionViewLayout = flowLayout    // 指定布局
        collection.isSelectable = true                  // item是否可以点击
        collection.register(NSNib.init(nibNamed: NSNib.Name.init("CKCollectionViewItem"), bundle: nil), forItemWithIdentifier: CKCollectionViewItem.identifier)
        //collection.register(CKCollectionViewItem.self, forItemWithIdentifier: CKCollectionViewItem.identifier)  // 注册Item 和NSCollectionView类似
        collection.register(CKHeaderView.self, forSupplementaryViewOfKind: NSCollectionView.elementKindSectionHeader, withIdentifier: CKHeaderView.identifier)
        
        collection.wantsLayer = true
        collection.layer?.backgroundColor = color_dark70.cgColor
        collection.isSelectable = true
        // 设置代理
        collection.delegate = self
        collection.dataSource = self
        return collection
    }()
    
    lazy var clipView: NSClipView = {
        let clipView = NSClipView.init(frame: CGRect.zero)
        clipView.documentView = self.collectionView;
        return clipView
    }()
    
    lazy var scrollView: NSScrollView = {
        let view = NSScrollView.init(frame: CGRect.zero)
        view.contentView = clipView;
        view.documentView?.enclosingScrollView?.scrollerInsets = NSEdgeInsetsMake(0, 0, 0, -30)
        return view
    }()
    
    override init(frame frameRect: NSRect) {
        super.init(frame: frameRect)
        self.setupSubviews()
        self.loadData()
    }
    
    required init?(coder decoder: NSCoder) {
        super.init(coder: decoder)
    }
    
    func loadData() {
        let cap = TXLiteManager.shared().getScreenCaptureSources(with: CGSize.init(width: 300, height: 300), iconSize: CGSize.init(width: 128, height: 128))
        if cap != nil {
            let capturable = cap! as NSArray
            let windowList = capturable.filtered(using: NSPredicate(format: "type = \(TRTCScreenCaptureSourceType.window.rawValue)")) as! [TRTCScreenCaptureSourceInfo]
            let screenList = capturable.filtered(using: NSPredicate(format: "type = \(TRTCScreenCaptureSourceType.screen.rawValue)")) as! [TRTCScreenCaptureSourceInfo]
            self.sections = [screenList,windowList]
            
            //self.configureCollectionView()
            self.collectionView.reloadData()
        }
        
    }
    
    public func configureCollectionView() {
        let layout = NSCollectionViewFlowLayout.init()
        layout.itemSize = NSSize.init(width: 160, height: 160)
        layout.sectionInset = NSEdgeInsetsMake(8, 28, 8, 28)
        layout.minimumLineSpacing = 30
        layout.minimumInteritemSpacing = 10
        self.collectionView.collectionViewLayout = layout
    }
    
    func setupSubviews() -> Void {
        self.addSubview(scrollView)
        scrollView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
    }
    
    /*
    func setupSubviewsConstraints() -> Void {
        NSLayoutConstraint.activate([
            scrollView.topAnchor.constraint(equalTo: (scrollView.superview?.topAnchor)!),
            scrollView.leftAnchor.constraint(equalTo: (scrollView.superview?.leftAnchor)!),
            scrollView.rightAnchor.constraint(equalTo: (scrollView.superview?.rightAnchor)!),
            scrollView.bottomAnchor.constraint(equalTo: (scrollView.superview?.bottomAnchor)!),
            ])
        scrollView.needsLayout = true
        //使用约束的话 下面这句话是必须有的 否则会影响window，导致window不能用鼠标改变大小
        scrollView.translatesAutoresizingMaskIntoConstraints = false
    }
    */
    
}

extension CKCollectionView: NSCollectionViewDataSource, NSCollectionViewDelegate {
    
    func numberOfSections(in collectionView: NSCollectionView) -> Int {
        return self.sections.count
    }
    
    func collectionView(_ collectionView: NSCollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.sections[section].count
    }
    /**
    返回我们的Item。这里有一个注意点：
    NSCollectionViewItem是继承自NSViewController。而在NSViewController的初始化方法中，默认回去寻找同名的IB，和UIViewController不同的是，在没有IB的时候，我们直接使用NSViewController.init()是不会有任何问题的，因为loadView方法中会为我们创建默认的view。但是NSViewController则不会，如果我们不手动实现loadView方法自己设置view的话，view不会被创建。所以如果如果遇到控制台说nib找不到的时候，可以重点看看是不是哪个控制器的view没有赋值。
    */
  
    func collectionView(_ collectionView: NSCollectionView, itemForRepresentedObjectAt indexPath: IndexPath) -> NSCollectionViewItem {
        let item = collectionView.makeItem(withIdentifier: CKCollectionViewItem.identifier, for: indexPath) as? CKCollectionViewItem
        let info = self.sections[indexPath.section][indexPath.item]
        item?.isSelect = false
        item?.iconImageV.image = info.thumbnail
        item?.ctitle.stringValue = info.sourceName!
        return item!
    }
    
    func collectionView(_ collectionView: NSCollectionView, viewForSupplementaryElementOfKind kind: NSCollectionView.SupplementaryElementKind, at indexPath: IndexPath) -> NSView {
        let view = collectionView.makeSupplementaryView(ofKind: NSCollectionView.elementKindSectionHeader, withIdentifier: CKHeaderView.identifier, for: indexPath) as? CKHeaderView
        let sections = ["桌面","窗口"]
        view?.title.stringValue = sections[indexPath.section]
        return view!
    }
    
    func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> NSSize {
        return NSSize.init(width: self.frame.width, height: 50)
    }
    
    // 点击方法
    func collectionView(_ collectionView: NSCollectionView, didSelectItemsAt indexPaths: Set<IndexPath>) {
        let val = (indexPaths as NSSet).anyObject() as? IndexPath
        let item = collectionView.item(at: val!) as? CKCollectionViewItem
        item?.isSelect = true
        
        let info = self.sections[val!.section][val!.item]
        self.delegate?.ck_collectionView(collectionView, didSelectItemsAt: indexPaths, info: info)
       
    }
    
    func collectionView(_ collectionView: NSCollectionView, didDeselectItemsAt indexPaths: Set<IndexPath>) {
        let val = (indexPaths as NSSet).anyObject() as? IndexPath
        let item = collectionView.item(at: val!) as? CKCollectionViewItem
        item?.isSelect = false
    }
    
}

// NSCollectionView的布局方法
extension CKCollectionView: NSCollectionViewDelegateFlowLayout {
    // 返回Item的size
    func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> NSSize {
        return NSSize.init(width: 160, height: 120)
    }
    
}

/*
extension CKCollectionView {
    override func scrollWheel(with event: NSEvent) {
        self.initialzeMouseTracking()
        super.scrollWheel(with: event)
    }
    override func viewDidMoveToWindow() {
        self.initialzeMouseTracking()
        super.viewDidMoveToWindow()
    }
    override func updateTrackingAreas() {
        self.initialzeMouseTracking()
        super.updateTrackingAreas()
    }
    
    func initialzeMouseTracking() {
        let trackingArea = NSTrackingArea.init(rect: self.bounds, options: [NSTrackingArea.Options.mouseEnteredAndExited,NSTrackingArea.Options.activeAlways], owner: self, userInfo: nil)
        self.addTrackingArea(trackingArea)
        
        let location = self.window?.mouseLocationOutsideOfEventStream
        let mouseLocation =  self.convert(location!, from: nil)
        if NSPointInRect(mouseLocation, self.bounds) == true {
            self.mouseEntered(with: NSEvent())
        }else {
            self.mouseExited(with: NSEvent())
        }
        
    }
}
*/
